<?php
//
//	file: forum_backend.php
//	author: ptirhiik
//	begin: 08/08/2003
//	version: 1.6.2 - 16/02/2007
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//

define('IN_PHPBB', true);
$phpbb_root_path = './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
$requester = 'forum_backend';
include($phpbb_root_path . 'common.' . $phpEx);
include($config->url('includes/class_forums'));

define('MAX_ITEMS_SYNDICATED', 15);
define('FORCE_GUEST', true);
define('WITH_TEXT', true);

class rss
{
	var $header_sent;
	var $footer_sent;
	var $board;
	var $data;
	var $cache_path;

	var $forum_ids;
	var $last_time;

	function rss()
	{
		global $config;

		$this->header_sent = false;
		$this->footer_sent = false;
		$this->cache_path = $config->data['cache_path'];
		$this->reset();

		// get board settings
		$this->board = array(
			'protocol' => ($config->data['cookie_secure']) ? 'https://' : 'http://',
			'name' => trim(preg_replace('#^\/?(.*?)\/?$#', '\1', trim($config->data['server_name']))),
			'port' => ($config->data['server_port'] <> 80) ? ':' . trim($config->data['server_port']) : '',
			'path' => trim(str_replace('//', '/', '/' . preg_replace('#^\/?(.*?)\/?$#', '\1', trim($config->data['script_path'])) . '/')),
		);
		$this->board['root'] = implode('', $this->board);
	}

	function reset()
	{
		$this->data = '';
		$this->forum_ids = '';
		$this->last_time = 0;
		$this->header_sent = false;
	}

	function read_cache($forum_id)
	{
		global $config;

		$this->reset();
		if ( $config->data['cache_disable_rss'] )
		{
			return;
		}

		$cache_file = 'rss_' . $forum_id;
		if ( @file_exists($config->url($this->cache_path . $cache_file)) )
		{
			@include($config->url($this->cache_path . $cache_file));
			if ( !empty($this->data) )
			{
				$this->header_sent = true;
			}
		}
	}

	function write_cache($forum_id, $forum_ids)
	{
		global $config;

		if ( $config->data['cache_disable_rss'] )
		{
			return;
		}

		$data = '<' . '?php

if ( !defined(\'IN_PHPBB\') )
{
	die(\'Hack attempt\');
}
$this->last_time = ' . time() . ';
$this->forum_ids = array(' . implode(', ', $forum_ids) . ');
$this->data = \'' . str_replace('\'', '\\\'', str_replace('\\', '\\\\', $this->data)) . '\';

?' . '>';

		// output to file
		$cache_file = $config->url($this->cache_path . 'rss_' . $forum_id);
		$handle = @fopen($cache_file, 'w');
		@flock($handle, LOCK_EX);
		@fwrite($handle, $data);
		@flock($handle, LOCK_UN);
		@fclose($handle);
		@umask(0000);
		@chmod($cache_file, 0644);
	}

	function send()
	{
		global $user;

		$agent = strtolower(empty($_SERVER['HTTP_USER_AGENT']) ? $_ENV['HTTP_USER_AGENT'] : $_SERVER['HTTP_USER_AGENT']);
		if ( strpos(' ' . $agent, 'firefox') || strpos(' ' . $agent, 'mozilla') )
		{
			header('Content-type: text/xml; charset=' . $user->lang('ENCODING'));
		}
		else
		{
			header('Content-type: application/rss+xml; charset=' . $user->lang('ENCODING'));
		}
		if ( !$this->header_sent )
		{
			$this->header();
		}
		if ( !$this->footer_sent )
		{
			$this->footer();
		}
		echo $this->data;
		exit;
	}

	function trap($reason)
	{
		$this->reset();
		$this->header();
		$this->data .= '
	<item>
		<title>Error</title>
		<description>' . $reason . '</description>
	</item>';
		$this->footer();
		$this->send();
	}

	function header()
	{
		global $config, $user;

		if ( $this->header_sent )
		{
			return;
		}
		$this->data = '<?xml version=\'1.0\' encoding=\'' . $user->lang('ENCODING') . '\' ?>
<rss version="2.0">
<channel>
	<title>' . _clean_html($config->data['sitename']) . '</title>
	<link>' . $this->board['root'] . '</link>
	<description>' . _clean_html($config->data['site_desc']) . '</description>' . $this->data;
		$this->header_sent = true;
		$this->footer_sent = false;
	}

	function item($row)
	{
		global $config, $user, $forums;

		if ( !$this->header_sent )
		{
			$this->header();
		}
		$this->data .= '
	<item>
		<title>' . _clean_html($row['topic_title']) . '</title>
		<link>' . $this->board['root'] . 'viewtopic.' . $config->ext . '?' . POST_TOPIC_URL . '=' . $row['topic_id'] . '</link>
		<description>' . $row['rss_description'] . '</description>
		<author>' . _clean_html($row['topic_last_username'] . '@' . $this->board['name']) . '</author>
		<pubDate>' . date('D, d M Y H:i:s O', $row['topic_last_time']) . '</pubDate>
	</item>';
	}

	function footer()
	{
		if ( $this->footer_sent )
		{
			return;
		}
		if ( !$this->header_sent )
		{
			$this->header();
		}
		$this->data .= '
</channel>
</rss>';
		$this->footer_sent = true;
	}
}

// forum_id
$forums = new forums();
$forums->read();
$forum_id = _read(POST_FORUM_URL, TYPE_INT, '', $forums->data);

// instantiate rss
$rss = new rss();
if ( defined('FORCE_GUEST') && FORCE_GUEST )
{
	// get language
	$user = new user();
	$user->read(ANONYMOUS);
	$userdata = $user->data;
	$user->data = array();
	$user->set($requester);

	// we regen the cache every hour
	$rss->read_cache($forum_id);
	if ( $rss->forum_ids && ($rss->last_time > (time() - 3600)) )
	{
		$rss->send();
	}
	$rss->reset();
}
else
{
	$userdata = session_pagestart($user_ip, PAGE_INDEX);
	$user->set($requester);
}
$user->get_cache(POST_FORUM_URL);

// get authorised forums
$tkeys = array_flip($forums->keys);
$min_idx = $tkeys[$forum_id];
$max_idx = $tkeys[ $forums->data[$forum_id]['last_child_id'] ];
unset($tkeys);

$forum_ids = array();
for ( $i = $min_idx; $i <= $max_idx; $i++ )
{
	if ( $user->auth(POST_FORUM_URL, 'auth_read', $forums->keys[$i]) )
	{
		$forum_ids[] = $forums->keys[$i];
	}
}
if ( empty($forum_ids) )
{
	$rss->trap('No forums authorised');
}

// get the topics
$sql = 'SELECT t.topic_id, t.forum_id, t.topic_title, t.topic_sub_title, t.topic_last_username, t.topic_last_time, u.username, t.topic_first_post_id
			FROM ' . TOPICS_TABLE . ' t
				LEFT JOIN ' . USERS_TABLE . ' u
					ON u.user_id = t.topic_last_poster
						AND u.user_id <> ' . ANONYMOUS . '
						AND t.topic_last_poster <> 0
			WHERE t.forum_id IN(' . implode(', ', $forum_ids) . ')
				AND t.topic_moved_id = 0
			ORDER BY t.topic_last_time DESC
			LIMIT ' . MAX_ITEMS_SYNDICATED;
if ( !$result = $db->sql_query($sql, false, __LINE__, __FILE__, false) )
{
	$rss->trap('SQL_failed: ' . $sql);
}

// let's go
$topics = array();
while ( $row = $db->sql_fetchrow($result) )
{
	$row['topic_last_username'] = !empty($row['username']) ? $row['username'] : (!empty($row['topic_last_username']) ? $row['topic_last_username'] : $user->lang('Guest'));
	$row['rss_description'] = empty($row['topic_sub_title']) ? _clean_html($user->lang($forums->data[ $row['forum_id'] ]['forum_name'])) : _clean_html($row['topic_sub_title']);
	if ( defined('WITH_TEXT') && WITH_TEXT )
	{
		$topics[ $row['topic_first_post_id'] ] = $row;
	}
	else
	{
		$rss->item($row);
	}
}
$db->sql_freeresult($result);

if ( defined('WITH_TEXT') && WITH_TEXT && !empty($topics) )
{
	$sql = 'SELECT post_id, post_text
				FROM ' . POSTS_TEXT_TABLE . '
				WHERE post_id IN(' . implode(', ', array_keys($topics)) . ')
				ORDER BY post_id DESC';
	if ( !$result = $db->sql_query($sql, false, __LINE__, __FILE__, false) )
	{
		$rss->trap('SQL_failed: ' . $sql);
	}
	while ( $row = $db->sql_fetchrow($result) )
	{
		$topics[ $row['post_id'] ]['rss_description'] = _un_htmlspecialchars(_clean_html(_clean_bbcode($row['post_text'])));
		if ( strlen($topics[ $row['post_id'] ]['rss_description']) > 255 )
		{
			$topics[ $row['post_id'] ]['rss_description'] = substr($topics[ $row['post_id'] ]['rss_description'], 0, 251) . ' ...';
		}
		$topics[ $row['post_id'] ]['rss_description'] = str_replace("\n", '<br />', htmlspecialchars($topics[ $row['post_id'] ]['rss_description']));
	}
	$db->sql_freeresult($result);

	foreach ( $topics as $dummy => $row )
	{
		$rss->item($row);
	}
}

$rss->write_cache($forum_id, $forum_ids);
$rss->send();

?>